package org.dna.wickwtui;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.dna.MetroApplication;
import org.dna.MetroSession;
import org.dna.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginPage extends WebPage {

    private static final Logger LOG = LoggerFactory.getLogger("LoginPage");

    private static class LoginForm extends StatelessForm {

        private String metroUsername;
        private String metroPassword;

        public LoginForm(String id) {
            super(id);
            setModel(new CompoundPropertyModel(this));
            add(new TextField("metroUsername"));
            add(new PasswordTextField("metroPassword"));
        }

        @Override
        public final void onSubmit() {
            if (signIn(metroUsername, metroPassword)) {
                if (!continueToOriginalDestination()) {
                    setResponsePage(getApplication().getHomePage());
                }
            } else {
                error("Unknown username/ password");
            }
        }

        /**
         * @return false if the user is not authenticated
         * */
        private boolean signIn(String username, String password) {
            if (username == null || password == null) {
                return false;
            }
            User user = findUser(username, password);
            if (user == null) {
                return false;
            }
            if (user.getPassword().equals(password)) {
                MetroSession.get().setUser(user);
                return true;
            } else {
                return false;
            }
        }

        private User findUser(String username, String password) {
            org.dna.metronomo.persistence.User dbUser = MetroApplication.get().getUserDAO().findUser(username, password);
            if (dbUser == null) {
                return null;
            }

            return new User(dbUser);
        }
    }

    public LoginPage() {
        // Create feedback panel and add to page
        final FeedbackPanel feedback = new FeedbackPanel("feedback");

        add(feedback);
        LoginForm form = new LoginForm("form");
        add(form);
    }
}
